package com.zhanglinwei.openApiServer.utils;

import com.zhanglinwei.common.utils.SQLInjectUtils;
import com.zhanglinwei.openApiClient.utils.SQLHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

import static com.zhanglinwei.openApiServer.constants.OpenApiVerifyConstant.ENTITY_CLASS_PACKAGE_NAME;

public class SQLVerifyUtils {

    private SQLVerifyUtils() {}

    public static boolean loadEntity(String entityClassFullPath) {
        if (StringUtils.isBlank(entityClassFullPath)) {
            return false;
        }

        int lastPackageIndex = entityClassFullPath.lastIndexOf(".");
        String packageName = entityClassFullPath.substring(0, lastPackageIndex);
        if (lastPackageIndex == 0 || (!ENTITY_CLASS_PACKAGE_NAME.equals(packageName))) {
            return false;
        }

        try {
            Class.forName(entityClassFullPath);
            return true;
        } catch (ClassNotFoundException ignore) {
        }

        return false;
    }

    public static boolean simpleLegalEntity(String entityClassFullPath) {
        if (StringUtils.isBlank(entityClassFullPath)) {
            return false;
        }

        int lastPackageIndex = entityClassFullPath.lastIndexOf(".");
        String packageName = entityClassFullPath.substring(0, lastPackageIndex);

        return lastPackageIndex != 0 && (ENTITY_CLASS_PACKAGE_NAME.equals(packageName));
    }

    public static boolean verifyColumn(Field[] allowFileds, Collection<String> columns) {
        Set<String> collect = Arrays.stream(allowFileds).map(item -> SQLHelper.camelToSnakeCase(item.getName())).collect(Collectors.toSet());
        return collect.containsAll(columns);
    }

    public static boolean verifySqlInject(Collection<String> names) {
        if (CollectionUtils.isEmpty(names)) {
            return true;
        }
        boolean hasInject = names.stream().anyMatch(SQLInjectUtils::hasInject);
        return !hasInject;
    }

    public static boolean verifyFunction(Collection<String> names) {

        return false;
    }
}
